package com.xzx.annotation.transaction;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import lombok.Data;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

/**
 * @author xinzhixuan
 * @version 1.0
 * @date 2025/5/8 16:11
 */
@EnableTransactionManagement
@Data
@ComponentScan("com.xzx.annotation.transaction")
@Configuration
public class Config {

    private String url;

    @Bean
    public DataSource dataSource() {
        HikariConfig hikariConfig = new HikariConfig();
        hikariConfig.setJdbcUrl("jdbc:mysql://172.25.224.78:3306/datafact?serverTimezone=GMT%2B8&useSSL=false&zeroDateTimeBehavior=convertToNull&socketTimeout=60000&autoReconnect=true&maxReconnects=15&useUnicode=true&characterEncoding=utf8&allowMultiQueries=true");
        hikariConfig.setUsername("private_cloud");
        hikariConfig.setPassword("Mdgx7!zXqRLtGf#Y5KXL");
        hikariConfig.setDriverClassName("com.mysql.cj.jdbc.Driver");
        return new HikariDataSource(hikariConfig);
    }

    @Bean
    public JdbcTemplate jdbcTemplate(DataSource dataSource) {
        // @Configuration 标注的类比较特殊，就算调用dataSource()这个方法，也不会产生新的对象，而是到容器中去获取对象
//        return new JdbcTemplate(dataSource());
        return new JdbcTemplate(dataSource);
    }

    // 事务管理器
    @Bean
    public DataSourceTransactionManager transactionManager(DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

}
